/**
 * WebSocket
 */
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import store from '@/store'
import http from '@/libs/http'

import { Notification, MessageBox, Message } from 'element-ui'

/**
 * 连接 Socket
 * 存在跨域问题，需使用域名访问，浏览器上不能使用IP
 */
const ConnectWebsocket = () => {
    const user = store.state.user
    // const url = 'http://localhost:6658/websocket'
    const url = 'http://api.bmc.biz.com/websocket'

    let sock = new SockJS(url)
    let stomp = Stomp.over(sock);
    stomp.debug = false; //调试模式
    stomp.connect({}, function(frame) {
        console.log('==================== WebSocket 连接成功 ====================')
        Message({ type: 'success', duration: 2000, message: 'WebSocket 连接成功' })

        //订阅消息(用于连接到WebSocket后返回的消息)
        // stomp.subscribe('/connect', function(response) {
        //     console.log(response.body);
        // })

        subscribeForceUnlineMessage(stomp)
        subscribeSystemMessage(stomp)
        subscribeUserMessage(stomp)

    }, function() {
        console.log('******************** WebSocket 连接失败 ********************')
        Message({ type: 'error', duration: 2000, message: 'WebSocket 连接失败' })
    });
}


/**
 * 订阅强制下线消息
 * @param {*} stomp
 */
const subscribeForceUnlineMessage = (stomp) => {
    const user = store.state.user
    stomp.subscribe('/user/'+user.id+'/force', function(response) {
        const data = JSON.parse(response.body)
        MessageBox({
            title: `通知`,
            message: data.text,
            closeOnClickModal: false
        }).then(res => {
            store.dispatch('FedLogOut')
            window.location.reload()
        })
    })
}

/**
 * 订阅系统消息
 */
const subscribeSystemMessage = (stomp) => {
    stomp.subscribe('/server/system/broadcast', function(response) {
        const data = JSON.parse(response.body)
        MessageBox({
            title: '系统消息',
            message: data.text
        })
    })
}

/**
 * 订阅用户消息
 */
const subscribeUserMessage = (stomp) => {
    const user = store.state.user
    stomp.subscribe('/user/'+user.id+'/message', function(response) {
        const data = JSON.parse(response.body)
        MessageBox({
            title: `来自[${data.fromName}]的消息`,
            message: data.text
        })
    })
}

export {
    ConnectWebsocket
} ;
